import React, { forwardRef, useState, useImperativeHandle } from 'react';
import { IconBox } from '@/components';
import { useGlobalVar } from '@/hooks';
import { getIcon } from '@/utils';
import { TCategory } from '@/types';

const defaultColor = '#dddddd';

type Props = { data: TCategory; children?: React.ReactNode };

export default forwardRef((props: Props, ref) => {
   const { categories } = useGlobalVar();
   const [data, setData] = useState(props.data ?? categories[0]);
   const handleSelect = (item: TCategory) => {
      setData(item);
   };
   useImperativeHandle(ref, () => ({
      value: data._id,
   }));

   return (
      <>
         <div
            className="p-4 rounded-lg mb-3 flex text-base justify-between text-white"
            style={{ background: data.color }}
         >
            <div className="flex items-center space-x-2 ">
               {getIcon(data.icon, {
                  type: 'white',
               })}
               <span>{data.category_name}</span>
            </div>
            <span className="text-sm flex items-center">{props.children}</span>
         </div>
         <div className="grid grid-cols-5 gap-y-2">
            {categories.map((item) => (
               <div
                  className="flex flex-col items-center"
                  key={item._id}
                  onClick={handleSelect.bind(null, item)}
               >
                  <IconBox
                     background={
                        data._id === item._id ? item.color : defaultColor
                     }
                  >
                     {getIcon(item.icon, { size: 22, type: 'white' })}
                  </IconBox>
                  <span className="color-disabled text-xs">
                     {item.category_name}
                  </span>
               </div>
            ))}
         </div>
      </>
   );
});
